package com.computergames.server;

import com.computergames.server.message.*;
import com.computergames.server.protocol.MessageCodecSharable;
import com.computergames.server.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class ClientTest {
    private static String roomName = null;
    public static void main(String[] args)
    {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.INFO);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(LOGGING_HANDLER);
                            ch.pipeline().addLast(MESSAGE_CODEC);
                            ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                                //在连接建立后，发送一个消息给服务器
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    LinkedHashSet<String> uniqueMembers = new LinkedHashSet<>();
                                    uniqueMembers.add("zhangsan");
                                    List<String> memberList = new ArrayList<>(uniqueMembers);
                                    ctx.writeAndFlush(new CreateRoomRequestMessage("zxc", "五子棋", memberList,"1"));
                                }
                            });
                        }
                    });
            Channel channel = bootstrap.connect("localhost", 8081).sync().channel();
            channel.closeFuture().sync();
        }catch (InterruptedException e){
            log.error("server error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
